package com.example.demo.Controller;

import com.example.demo.Entity.Result;
import com.example.demo.Entity.User;
import com.example.demo.Service.FileService;
import com.example.demo.Service.UserService;
import com.example.demo.Service.UserServiceImp;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.Console;
import java.io.File;
import java.util.Map;


/**
 * 用户信息表前端操作接口
 **/
@CrossOrigin
@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private FileService fileService;

    /** 新增用户 */
    @PostMapping("/insert")
    public void insertUser(@RequestBody User user) {
        userService.insertUser(user);
    }

    /** 查询用户 */
    @GetMapping("/selectById")
    public User findById(@RequestParam Integer id) {
        return userService.selectById(id);
    }

    /** 删除用户 */
    @GetMapping("/deleteById/{id}")
    public Integer deleteById(@PathVariable("id") Integer id) {
        return userService.deleteById(id);
    }

    /** 更新用户 */
    @PostMapping("/update")
    public void update(@RequestBody User user) {
        userService.update(user);
    }

    /** 更新用户 */
    @PostMapping("/tupdate")
    public Integer testUpdate(@RequestBody Integer id) {
        return userService.testUpdateById(id);
    }

    /** 查询用户 */
    @ApiOperation("根据名字查找用户")
    @GetMapping("/selectByName")
    public User getUserByName(@RequestParam String name) {
        return userService.FindUserByName(name);
    }

    @PostMapping("/register")
    public Result register(@RequestBody User user){
        User u = userService.FindUserByName(user.getUsername());
        if(u == null){
            userService.register(user.getUsername(),user.getPassword());
            return Result.success();
        }
        else {
            return Result.error("用户名已被注册");
        }
    }

    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        User user0 = userService.FindUserByName(user.getUsername());
        if (user0 == null) {
            return Result.error("用户名不存在");
        } else {
            String password2 = userService.FindPasswordByName(user.getUsername());
            if (user.getPassword().equals(password2)) {
                return Result.success(user0);
            }
            else{
                return Result.error("密码错误");
            }
        }
    }

    /** 上传文件 */
    @PostMapping("/uploadFile")
    public String uploadFile(@RequestParam MultipartFile file){
        return fileService.upload(file);
    }

    /** 获取文件 */
    @GetMapping("/getFile/{flag}")
    public void getFile(@PathVariable String flag, HttpServletResponse response) {
        fileService.avatarPath(flag,response);
    }

    /** 删除文件 */
    @DeleteMapping("deleteFile/{flag}")
    public void deleteFile(@PathVariable String flag){
        fileService.delFile(flag);
    }

    /**上传头像*/
    @PostMapping("/uploadImg")
    public String UploadImg(@RequestParam MultipartFile headImg) {
        // 校验图片格式
        if (!userService.imageTypeRight(headImg)) return "图片格式不正确";

        try {
            // 保存文件
            userService.takeFile(headImg);

            // 获取上传文件后的路径
            String path = "D:\\Avatar" + "\\" + headImg.getOriginalFilename();

            // 更新用户信息
           // User user = new User(); // 获取当前用户的逻辑需要根据具体情况实现
          //  user = userService.FindUserByName(username);
          //  user.setAvatar(path)


            // 假设有更新用户信息到数据库的逻辑
          //  userService.update(user);

            return path;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("上传头像失败");
            return "上传失败";
        }
    }

    /** 删除用户 */
    @GetMapping("/downAvatar")
    public File downAvatar(@RequestParam String filename) {
        System.out.println("路径为"+"D:\\Avatar"+"\\"+filename);
        File file = new File("D:\\Avatar"+"\\"+filename);

        return file;
    }
    @PatchMapping("updatePWD")
    public Result updatePWD(@RequestBody Map<String,String> map) {
        String old_password = map.get("old_password");
        String new_password = map.get("new_password");
        String re_password = map.get("re_password");
        String username = map.get("username");
        String real_password =userService.FindPasswordByName(username);

        if(!StringUtils.hasLength(old_password) || !StringUtils.hasLength(new_password)|| !StringUtils.hasLength(re_password)){
            return Result.error("输入不规范");
        }

        if(!StringUtils.hasLength(real_password)){
            return Result.error("用户名不存在");
        }

        if(!old_password.equals(real_password)){
            return Result.error("旧密码不正确");
        }

        if(!new_password.equals(re_password)){
            return Result.error("两次填写密码不一致");
        }
        userService.updatePWD(new_password,username);
        return Result.success();
    }
}
